package com.mbl.base.modular.base.controller;

import com.alibaba.fastjson.JSON;
import com.mbl.base.config.security.SecurityUser;
import com.mbl.base.core.common.dto.MblResult;
import com.mbl.base.core.common.exception.AuthException;
import com.mbl.base.core.utils.UtilJwtToken;
import com.mbl.base.core.utils.UtilSecurity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private UserDetailsService userDetailsService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public MblResult login(String username, String password){
        if (StringUtils.isAnyBlank(username, password)) {
            throw new AuthException("账号或密码为空！");
        }
        final UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if(userDetails == null){
            throw new AuthException("找不到该用户！");
        }
        if(!new BCryptPasswordEncoder().matches(password, userDetails.getPassword())){
            throw new AuthException("密码错误！");
        }
        final String token = UtilJwtToken.generateToken(userDetails);
        final HashMap<Object, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", userDetails);
        return MblResult.success(result);
    }
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public MblResult info(){
        final SecurityUser user = UtilSecurity.getUser();
        return MblResult.success(user);
    }
}
